package kuangshen.lock;

/**
 * @program: liangt
 * @description: 管程法
 * @author: liangt
 * @create: 2021-03-03 16:38
 */
//生产者、消费者、缓存区、产品
public class TestPC {
    public static void main(String[] args) {
        Synchronoized synchronoized = new Synchronoized();

        new Productor(synchronoized).start();
        new Consumer(synchronoized).start();
    }
}

//消费者
class Consumer extends Thread{
    Synchronoized synchronoized;
    public Consumer (Synchronoized synchronoized){
        this.synchronoized = synchronoized;
    }
    @Override
    public void run() {
        super.run();
        for (int i = 0; i < 100; i++) {
            synchronoized.pop();
            System.out.println("消费了第"+i+"个苹果");
        }
    }
}

//生产者
class Productor extends Thread{
    Synchronoized synchronoized;
    public Productor(Synchronoized synchronoized){
        this.synchronoized = synchronoized;
    }
    @Override
    public void run() {
        super.run();
        for (int i = 0; i < 100; i++) {
            Apple apple = new Apple();
            synchronoized.push(apple);
            System.out.println("生产了第"+i+"个苹果");
        }
    }
}

class Apple{

}
//通道
class Synchronoized{
    //数据
    Apple[] apples = new Apple[10];
    //计数器
    int counts = 0;

    //生产者生产苹果
    public synchronized void push(Apple apple){
        //如果苹果满了则暂停生产
        if (counts == apples.length){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //生产苹果
        apples[counts] = apple;
        counts++;
        this.notifyAll();//唤醒所有沉睡线程
    }

    //消费者消费苹果
    public synchronized  void pop(){
        //如果没有苹果则暂停消费
        if (counts == 0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        counts--;
        apples[counts] = null;
        this.notifyAll();//唤醒线程
    }
}